package org.nmgyjt.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nimbusds.jose.JOSEException;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.entity.admin.*;
import org.nmgyjt.springboot.entity.area.Area;
import org.nmgyjt.springboot.mapper.CsSystemSourcePreSetInfoMapper;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.HttpUtils;
import org.nmgyjt.springboot.utils.NMGYJTIDAASTokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-10-06
 */
@Service
public class CsSystemSourcePreSetInfoServiceImpl extends ServiceImpl<CsSystemSourcePreSetInfoMapper, CsSystemSourcePreSetInfo> implements ICsSystemSourcePreSetInfoService {

    @Autowired
    ICsSystemSourceExtService extService;

    @Autowired
    ICsSystemSourceTypeService sourceTypeService;

    @Autowired
    ICsSystemAdminService adminService;

    @Autowired
    CsSystemDeptServiceImpl deptService;

    @Autowired
    IAreaService areaService;

    @Autowired
    ICsSystemSourceExtService csSystemSourceExtService;

    @Autowired
    ICsSystemSourceTypeService iCsSystemSourceTypeService;


    @Override
    public CsSystemStatisticSourcePreSetMountResponse statisticSourcePreSetInfos(CsSystemStatisticSourcePreSetMountBean bean) {
        CsSystemStatisticSourcePreSetMountResponse mountResponse = new CsSystemStatisticSourcePreSetMountResponse();
        int unhandled = 0;
        List<String> unhandledData = new ArrayList<>();
        List<String> preSetDataResponse = new ArrayList<>();
        CsSystemSourcePreSetInfo preSetInfo = this.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, bean.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, bean.getMenuId()).orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
        if (null != preSetInfo) {
            mountResponse.setOrgId(bean.getOrgId());
            if (!StringUtils.isEmpty(preSetInfo.getPreSetTypes())) {
                List<String> preSetData = JSONObject.parseObject(preSetInfo.getPreSetTypes(), List.class);
                mountResponse.setPreSetData(preSetData);
                if (!CollectionUtils.isEmpty(preSetData) && preSetData.size() > 0) {
                    mountResponse.setPreSetMount(preSetData.size());
                    List<CsSystemSourceExt> sourceExt = extService.list(new LambdaQueryWrapper<CsSystemSourceExt>()
                            .eq(CsSystemSourceExt::getSuperiorOrgId, bean.getOrgId()));
                    for (String sourceId : preSetData) {
                        CsSystemSourceType type = sourceTypeService.getById(sourceId);
                        if (null != type) {
                            preSetDataResponse.add(type.getName());
                        }
                        if (null == sourceExt || (null != sourceExt && !JSONObject.toJSONString(sourceExt).contains(sourceId))) {
                            unhandled = unhandled + 1;
                            unhandledData.add(type.getName());
                        }
                    }
                } else {
                    mountResponse.setPreSetMount(0);
                }
            } else {
                mountResponse.setPreSetMount(0);
            }
        } else {
            mountResponse.setPreSetMount(0);
        }
        mountResponse.setUnhandledPreSetMount(unhandled);
        mountResponse.setUnhandledPreSetData(unhandledData);
        mountResponse.setPreSetData(preSetDataResponse);

        return mountResponse;
    }

    @Override
    public CsSystemSourcePreSetInfoResponse selectSourcePreSetInfos(CsSystemStatisticSourcePreSetMountBean bean) throws ParseException, JOSEException {

        CsSystemSourcePreSetInfo preSetInfo = this.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, bean.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, bean.getMenuId()).orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
        CsSystemSourcePreSetInfoResponse infoResponse = new CsSystemSourcePreSetInfoResponse();
        List<CsSystemSourceType> sourceTypes1 = new ArrayList<>();
        List<IDAASDeptResponse> listResponse = new ArrayList<>();
        List<CsSystemAdminAndOrgInfo> adminsAndDeptInfos = new ArrayList<>();

        infoResponse.setMenuId(bean.getMenuId());
        infoResponse.setOrgId(bean.getOrgId());
        if (null != preSetInfo) {
            List<Object> preSetData = JSONObject.parseObject(preSetInfo.getPreSetTypes(), List.class);
            if (!CollectionUtils.isEmpty(preSetData)) {
                for (Object str : preSetData) {
                    List<String> list = Arrays.asList(str.toString().replace("\"[", "").replace("]\"", "").replace("[", "").replace("]", "").replace("\"", "").split(","));
                    sourceTypes1.add(sourceTypeService.getById(list.get(list.size() - 1)));
                }

            }
        }
        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        HashMap<String, String> bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");

        if (("1000000012".equals(bean.getMenuId()) || "1000000014".equals(bean.getMenuId())) && !CollectionUtils.isEmpty(sourceTypes1)) {

            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + bean.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);


            String orgTypeName = "1000000012".equals(bean.getMenuId())? "防护目标":"避难场所";
            if ( StringUtils.isNotEmpty(str1) && str1.contains(orgTypeName)) {
                IDAASDeptResponse deptResponse = deptService.getOrgInfoFromIDAASOrgList(str1, orgTypeName);

                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                List<IDAASDeptResponse> resourceDepts = JSONArray.parseArray(str2, IDAASDeptResponse.class);

                if (!CollectionUtils.isEmpty(resourceDepts)) resourceDepts.forEach(dept -> {
                    if (!"管理员".equals(dept.getValues().getName()) && "ENABLED".equals(dept.getValues().getStatus()))
                        listResponse.add(dept);
                });

            }


            if (!CollectionUtils.isEmpty(listResponse)) {
                for (IDAASDeptResponse dept : listResponse) {
                    if ("ENABLED".equals(dept.getValues().getStatus())) {
                        CsSystemAdminAndOrgInfo csSystemAdmin = new CsSystemAdminAndOrgInfo();

                        List<CsSystemAdmin> admins = adminService.list(
                                CsSystemAdmin.gw().eq(CsSystemAdmin::getOrgId, dept.getId()));
                        if (CollectionUtils.isEmpty(admins)) {
                            csSystemAdmin.setOrgName(dept.getValues().getName());
                            csSystemAdmin.setOrgId(dept.getId());
                            csSystemAdmin.setSuperiorOrg(bean.getOrgId());
                            csSystemAdmin.setUdOrder(Integer.valueOf(dept.getValues().getUdOrder()));
                            csSystemAdmin.setName("");
                            csSystemAdmin.setJob("");
                            csSystemAdmin.setPhone("");
                            csSystemAdmin.setOffice("");
                            csSystemAdmin.setId("");
                            if ("1000000007".equals(bean.getMenuId())) {
                                csSystemAdmin.setOffice(dept.getValues().getName());
                            }
                        } else {
                            BeanUtils.copyProperties(admins.get(admins.size() - 1), csSystemAdmin);
                            csSystemAdmin.setOrgName(dept.getValues().getName());
                            if ("1000000007".equals(bean.getMenuId())) {
                                csSystemAdmin.setOffice(dept.getValues().getName());
                            }
                            //获取机构的预设成员单位数据
                            String permissionStr = csSystemAdmin.getMenuPermission().replace("::", "");
                            permissionStr = permissionStr.replace(":", ",");
                            if (StringUtils.isNotEmpty(permissionStr)) {
                                List<String> permissionList = Arrays.asList(permissionStr.split(","));
                                List<CsSystemOrgPreSetBean> preSetOrgInfos = new ArrayList<>();
                                if (!CollectionUtils.isEmpty(permissionList)) {
                                    for (String p : permissionList) {
                                        CsSystemOrgPreSetBean preSetBean = new CsSystemOrgPreSetBean();

                                        if ("1000000007".equals(p)) {

                                            String preSetOfficeUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + dept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                                            String preSetOfficeStr = HttpUtils.httpGet(preSetOfficeUrl, bodyParams, headerParams);
                                            IDAASDeptResponse interDeptResponse = deptService.getOrgInfoFromIDAASOrgList(preSetOfficeStr, "内设机构");

                                            String preSetOfficeDetailUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_regionCode&order_by=_udOrder&order_by=_createdOn";
                                            String preSetOfficeStrDetail = HttpUtils.httpGet(preSetOfficeDetailUrl, bodyParams, headerParams);
                                            List<IDAASDeptResponse> responseList = JSONArray.parseArray(preSetOfficeStrDetail, IDAASDeptResponse.class);
                                            List<CsSystemOrgItemPreSetBean> offices = new ArrayList<>();
                                            if (!CollectionUtils.isEmpty(responseList)) {
                                                HashMap bodyParams2 = new HashMap<>();
                                                Map bodyParam1 = new HashMap();
                                                bodyParam1.put("status", new ArrayList<>());
                                                bodyParam1.put("identityClassification", "defaultIdentityClassification");
                                                bodyParams.put("objectType", "USER");

                                                responseList.forEach(o -> {
                                                    CsSystemOrgItemPreSetBean office = new CsSystemOrgItemPreSetBean();
                                                    office.setMaxUserNumber(o.getValues().getMaxUserNumber());


                                                    List<String> orgId = new ArrayList<>();
                                                    orgId.add(o.getId());
                                                    bodyParam1.put("deptId", orgId);
                                                    bodyParams2.put("values", bodyParam1);
                                                    bodyParams2.put("objectType", "USER");
                                                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + o.getId() + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                                                    String str2 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams2), headerParams);
                                                    IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);
                                                    office.setUserNumber(object.getTotal());
                                                    offices.add(office);
                                                });
                                            }
                                            preSetBean.setOrgChildren(offices);
                                        }

                                        if ("1000000012".equals(p)) {
                                            CsSystemSourcePreSetInfo one = this.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, csSystemAdmin.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, p).orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
                                            if (null != one && !StringUtils.isEmpty(one.getPreSetTypes()))
                                                preSetBean.setChildren(JSONObject.parseObject(one.getPreSetTypes(), List.class));
                                        }
                                        preSetBean.setId(p);
                                        preSetOrgInfos.add(preSetBean);

                                    }
                                    csSystemAdmin.setPreSetOrgInfos(preSetOrgInfos);
                                }

                            }
                        }
                        if (null != dept.getValues() && StringUtils.isNotEmpty(dept.getValues().getRegionCode())) {
                            Area area = areaService.getById(StringUtils.rightPad(dept.getValues().getRegionCode(), 12, "0"));
                            if (null != area) {
                                csSystemAdmin.setAreaCode(area.getId());
                                csSystemAdmin.setAreaName(area.getName());
                            }
                        }

                        String[] menus = {"1000000010", "1000000011", "1000000012", "1000000014"};
                        List<String> menuList = Arrays.asList(menus);
                        CsSystemSourceLevelBean sourceExt = new CsSystemSourceLevelBean();
                        sourceExt.setCountry("");
                        if (null != bean.getMenuId() && menuList.contains(bean.getMenuId())) {
                            List<CsSystemSourceExt> sourceExts =
                                    csSystemSourceExtService.list(new LambdaQueryWrapper<CsSystemSourceExt>()
                                            .eq(CsSystemSourceExt::getMenuId, bean.getMenuId())
                                            .eq(CsSystemSourceExt::getOrgId, dept.getId())
                                            .orderByDesc(CsSystemSourceExt::getId).last("limit 1"));
                            if (null != sourceExts && !CollectionUtils.isEmpty(sourceExts)) {
                                csSystemAdmin.setSuperiorOrg(sourceExts.get(0).getSuperiorOrgName());
                                if (null != sourceExts.get(0).getSourceType() && sourceExts.get(0).getSourceType().contains("[") && sourceExts.get(0).getSourceType().contains("]")) {
                                    csSystemAdmin.setSourceType(JSONArray.parseObject(sourceExts.get(0).getSourceType(), List.class));
                                    if (!CollectionUtils.isEmpty(csSystemAdmin.getSourceType())) {
                                        List<String> sourceTypes = csSystemAdmin.getSourceType();
                                        if (null != sourceTypes && sourceTypes.size() > 0) {
                                            csSystemAdmin.getSourceType().forEach(type -> {
                                                if (type.contains("::")) {
                                                    String[] split = type.split("::");
                                                    List<String> typeList = Arrays.asList(split);
                                                    for (String ty : typeList) {
                                                        CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(ty);
                                                        if (StringUtils.isNotEmpty(csSystemAdmin.getSourceTypeValue()) && null != csSystemSourceType) {
                                                            csSystemAdmin.setSourceTypeValue(csSystemAdmin.getSourceTypeValue() + csSystemSourceType.getName() + "，");
                                                        } else if (null != csSystemSourceType) {
                                                            csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                        }
                                                    }
                                                } else {
                                                    CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(type);
                                                    if (StringUtils.isNotEmpty(csSystemAdmin.getSourceTypeValue()) && null != csSystemSourceType) {
                                                        csSystemAdmin.setSourceTypeValue(csSystemAdmin.getSourceTypeValue() + csSystemSourceType.getName() + "，");
                                                    } else if (null != csSystemSourceType) {
                                                        csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                    }
                                                }
                                            });
                                        }
                                    }
                                } else if (null != sourceExts.get(0) && StringUtils.isNotEmpty(sourceExts.get(0).getSourceType())) {
                                    csSystemAdmin.setSourceType(Arrays.asList(sourceExts.get(0).getSourceType().split(",")));
                                    if (!CollectionUtils.isEmpty(csSystemAdmin.getSourceType())) {
                                        csSystemAdmin.getSourceType().forEach(type -> {

                                            if (type.contains("::")) {
                                                String[] split = type.split("::");
                                                List<String> typeList = Arrays.asList(split);
                                                for (String ty : typeList) {
                                                    CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(ty);
                                                    if (StringUtils.isNotEmpty(csSystemAdmin.getSourceTypeValue()) && null != csSystemSourceType) {
                                                        csSystemAdmin.setSourceTypeValue(csSystemAdmin.getSourceTypeValue() + csSystemSourceType.getName() + "，");
                                                    } else if (null != csSystemSourceType) {
                                                        csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                    }
                                                }
                                            } else {
                                                CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(type);
                                                if (null != csSystemSourceType && ("1000000010".equals(bean.getMenuId()) || "1000000012".equals(bean.getMenuId()))) {
                                                    CsSystemSourceType parentSourceType = iCsSystemSourceTypeService.getById(csSystemSourceType.getParentId());

                                                    csSystemAdmin.setSourceTypeValue(parentSourceType.getName() + csSystemSourceType.getName() + "，");
                                                } else if (null != csSystemSourceType) {

                                                    csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                }
                                            }
                                        });
                                    }
                                } else {
                                    csSystemAdmin.setSourceType(new ArrayList<>());
                                    csSystemAdmin.setSourceTypeValue("");
                                }

                                if (null != sourceExts.get(0).getSourceLevel()) {
                                    CsSystemSourceLevelBean levelBean = JSONObject.parseObject(sourceExts.get(0).getSourceLevel(), CsSystemSourceLevelBean.class);
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCountry()))
                                        sourceExt.setCountry(levelBean.getCountry());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getProvince()))
                                        sourceExt.setProvince(levelBean.getProvince());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCity()))
                                        sourceExt.setCity(levelBean.getCity());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCounty()))
                                        sourceExt.setCounty(levelBean.getCounty());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCityOrgId()))
                                        sourceExt.setCityOrgId(levelBean.getCityOrgId());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCityOrgName()))
                                        sourceExt.setCityOrgName(levelBean.getCityOrgName());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCountyOrgId()))
                                        sourceExt.setCountyOrgId(levelBean.getCountyOrgId());
                                    if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCountyOrgName()))
                                        sourceExt.setCountyOrgName(levelBean.getCountyOrgName());
                                }
                            }
                        }
                        csSystemAdmin.setSourceLevel(sourceExt);
                        adminsAndDeptInfos.add(csSystemAdmin);
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(sourceTypes1)) {
            for (CsSystemSourceType source : sourceTypes1) {
                List<CsSystemAdminAndOrgInfo> orgs = new ArrayList<>();
                for (CsSystemAdminAndOrgInfo info : adminsAndDeptInfos) {
                    if (null !=info.getSourceType() && source.getId().equals(info.getSourceType().get(0))) {
                        orgs.add(info);
                    }
                }
                source.setMount(orgs.size());
                source.setOrgs(orgs);
            }
        }
        infoResponse.setPreSetSources(sourceTypes1);
        return infoResponse;
    }

    @Override
    public CsSystemSourcePreSetInfoResponse updateSourcePreSetInfos(CsSystemSourcePreSetUpdateBean bean) throws ParseException, JOSEException {

        return null;
    }
}
